<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="小组名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入小组名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="小组编号" prop="teamCode">-->
<!--        <el-input-->
<!--          v-model="queryParams.teamCode"-->
<!--          placeholder="请输入小组编号"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="小组经理" prop="managerId">
<!--        <el-input-->
<!--          v-model="queryParams.managerId"-->
<!--          placeholder="请输入小组经理ID，关联销售人员表的员工ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
        <el-select v-model="queryParams.managerId" clearable
                  @keyup.enter="handleQuery"
                  class="!w-240px"
                   placeholder="请选择小组经理">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="departmentId">
<!--        <el-input-->
<!--          v-model="queryParams.departmentId"-->
<!--          placeholder="请输入所属部门ID，关联部门表"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
        <el-select v-model="queryParams.departmentId" clearable
                   @keyup.enter="handleQuery"
                   class="!w-240px"
                   placeholder="请选择所属部门">
          <el-option
            v-for="item in deptList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="销售目标金额" prop="teamGoal">-->
<!--        <el-input-->
<!--          v-model="queryParams.teamGoal"-->
<!--          placeholder="请输入销售目标金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="销售目标" prop="currentQuarterTarget">-->
<!--        <el-input-->
<!--          v-model="queryParams.currentQuarterTarget"-->
<!--          placeholder="请输入本季度销售目标"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="小组状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择小组状态"
          clearable
          class="!w-240px"
        >
          <el-option label="活跃" value="1" />
          <el-option label="已解散" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售区域" prop="region">
        <el-input
          v-model="queryParams.region"
          placeholder="请输入销售区域"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="销售产品类别" prop="productFocus">
        <el-input
          v-model="queryParams.productFocus"
          placeholder="请输入销售产品类别"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="成立日期" prop="establishmentDate">
        <el-date-picker
          v-model="queryParams.establishmentDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合作模式" prop="contractType">
        <el-select
          v-model="queryParams.contractType"
          placeholder="请选择合作模式"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_SALES_CONTRACT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="创建时间" prop="createTime">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.createTime"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['saleTeam:biz-sales-team:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['saleTeam:biz-sales-team:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['saleTeam:biz-sales-team:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
<!--      <el-table-column label="小组ID" align="center" prop="teamId" />-->
      <el-table-column label="小组名称" align="center" prop="teamName" />
      <el-table-column label="小组编号" align="center" prop="teamCode" />
      <el-table-column label="小组经理" align="center" prop="managerId" >
        <template #default="scope">
          {{ userList.find((user) => user.id === scope.row.managerId)?.nickname }}
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="departmentId" >
        <template #default="scope">
          {{ deptList.find((user) => user.id === scope.row.departmentId)?.name }}
        </template>
      </el-table-column>
      <el-table-column label="合作模式" align="center" prop="contractType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_SALES_CONTRACT_TYPE" :value="scope.row.contractType" />
        </template>
      </el-table-column>

      <el-table-column label="销售目标金额" align="center" prop="teamGoal" />
<!--      <el-table-column label="本季度销售目标" align="center" prop="currentQuarterTarget" />-->
<!--      <el-table-column label="小组描述信息" align="center" prop="teamDescription" />-->
      <el-table-column label="成立日期" align="center" prop="establishmentDate" >
        <template #default="scope">
          {{formatDate(scope.row.establishmentDate,'YYYY-MM-DD')}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <el-tag v-if="scope.row.status == '1'" type="success">活跃</el-tag>
          <el-tag v-else-if="scope.row.status == '0'" type="danger">已解散</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销售区域" align="center" prop="region" />
      <el-table-column label="销售产品类别" align="center" prop="productFocus" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.teamId)"
            v-hasPermi="['saleTeam:biz-sales-team:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.teamId)"
            v-hasPermi="['saleTeam:biz-sales-team:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BizSalesTeamForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BizSalesTeamApi, BizSalesTeam } from '@/api/biz/salesteam'
import BizSalesTeamForm from './BizSalesTeamForm.vue'
import * as UserApi from "@/api/system/user";
import {handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

/** 销售团队信息 列表 */
defineOptions({ name: 'BizSalesTeam' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userList = ref<DeptApi.DeptVO[]>([]) // 用户列表
const deptList = ref<UserApi.UserVO[]>([]) // 用户列表
import { formatDate } from '@/utils/formatTime'

const loading = ref(true) // 列表的加载中
const list = ref<BizSalesTeam[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  teamName: undefined,
  teamCode: undefined,
  managerId: undefined,
  departmentId: undefined,
  teamGoal: undefined,
  currentQuarterTarget: undefined,
  teamDescription: undefined,
  establishmentDate: [],
  status: undefined,
  region: undefined,
  productFocus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BizSalesTeamApi.getBizSalesTeamPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BizSalesTeamApi.deleteBizSalesTeam(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除销售团队信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await BizSalesTeamApi.deleteBizSalesTeamList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: BizSalesTeam[]) => {
  checkedIds.value = records.map((item) => item.teamId);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BizSalesTeamApi.exportBizSalesTeam(queryParams)
    download.excel(data, '销售团队信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  userList.value = await UserApi.getSimpleUserList()
  deptList.value = await DeptApi.getSimpleDeptList()

})
</script>
